<?php

/**
 * 计算用户的答题正确/错误数量并且入库到用户表
 */

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UserTableQuestionCountCalculateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int $userId;
    protected int $type;    // 1：正确的题、2：错误的题

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $type)
    {
        $this->userId = $userId;
        $this->type = $type;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = DB::table('user')->find($this->userId);

        if ($user) {
            $count = DB::table('qh_user_question_logs')
                ->select(DB::raw('COUNT(*) as count'))
                ->where('userId', $this->userId)
                ->where('result', $this->type)
                ->value('count');

            $countOfToday = DB::table('qh_user_question_logs')
                ->select(DB::raw('COUNT(*) as count'))
                ->where('userId', $this->userId)
                ->where('result', $this->type)
                ->whereBetween('created_at', [now()->startOfDay(), now()->endOfDay()])
                ->value('count');

            if ($this->type == 1) $update = ['correctQuestionCount' => $count, 'correctQuestionCountOfToday' => $countOfToday];
            if ($this->type == 2) $update = ['wrongQuestionCount' => $count, 'wrongQuestionCountOfToday' => $countOfToday];

            if (isset($update)) {
                DB::table('user')->where('id', $this->userId)->update($update);
            }
        }
    }
}
